﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;
using System.IO.Compression;

namespace Utils
{
    public class WebRequestHelper
    {
        public static string CreateStrHttpResponse(string url, IDictionary<string, string> parameters, Encoding requestEncoding)
        {
            var response = CreateHttpResponse(url, parameters, requestEncoding);
            string html = string.Empty;

            if (response != null)
            {
                // 得到返回的数据流
                Stream receiveStream = response.GetResponseStream();
                // 如果有压缩,则进行解压
                if (response.ContentEncoding.ToLower().Contains("gzip"))
                {
                    receiveStream = new GZipStream(receiveStream, CompressionMode.Decompress);
                }
                // 得到返回的字符串  
                html = new StreamReader(receiveStream).ReadToEnd();
            }
            return html;
        }

        public static HttpWebResponse CreateHttpResponse(string url, IDictionary<string, string> parameters, Encoding requestEncoding)
        {
            if (string.IsNullOrEmpty(url))
            {
                throw new ArgumentNullException("url");
            }

            if (requestEncoding == null)
            {
                throw new ArgumentNullException("requestEncoding");
            }

            HttpWebRequest request = null;

            //如果是发送HTTPS请求
            if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
            {
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                request = WebRequest.Create(url) as HttpWebRequest;
                request.ProtocolVersion = HttpVersion.Version10;
            }
            else
            {
                request = WebRequest.Create(url) as HttpWebRequest;
            }
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            //如果需要POST数据
            if (!(parameters == null || parameters.Count == 0))
            {
                StringBuilder buffer = new StringBuilder();
                int i = 0;
                foreach (string key in parameters.Keys)
                {
                    if (i > 0)
                    {
                        buffer.AppendFormat("&{0}={1}", key, parameters[key]);
                    }
                    else
                    {
                        buffer.AppendFormat("{0}={1}", key, parameters[key]);
                    }
                    i++;
                }
                byte[] data = Encoding.UTF8.GetBytes(buffer.ToString());
                using (Stream stream = request.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                }
            }
            return request.GetResponse() as HttpWebResponse;
        }

        private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            return true; //总是接受
        }


        public static string GetPageHTML(string url, string referer = "")
        {
            return GetPageHTML(url, Encoding.UTF8, referer);
        }

        /// <summary>
        /// 获取指定字符编码的页面HTML代码
        /// </summary>
        /// <param name="url">页面地址</param>
        /// <param name="encoding">字符编码</param>
        /// <returns>指定URL的Html代码</returns>
        public static string GetPageHTML(string url, Encoding encoding, string referer = "")
        {
            Stream stream = null;
            StreamReader sr = null;

            try
            {
                var req = (HttpWebRequest)WebRequest.Create(url);
                req.Method = "GET";
                req.Accept = "text/html,application/xhtml+xml,application/xml;";
                req.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.111 Safari/537.36";
                if (!string.IsNullOrEmpty(referer))
                {
                    req.Referer = referer;
                }
                req.Timeout = 1000 * 300;//500秒
                req.ReadWriteTimeout = 1000 * 300;
                var response = (HttpWebResponse)req.GetResponse();
                stream = response.GetResponseStream();
                sr = new StreamReader(stream, encoding);
                return sr.ReadToEnd();
            }
            catch
            {
                return string.Empty;
            }
            finally
            {
                if (sr != null)
                {
                    sr.Close();
                    sr.Dispose();
                }

                if (stream != null)
                {
                    stream.Close();
                    stream.Dispose();
                }
            }
        }


        /// <summary>
        /// 获取指定字符编码的页面HTML代码
        /// </summary>
        /// <param name="url">页面地址</param>
        /// <param name="encoding">字符编码</param>
        /// <param name="responseUrl">302跳转后的url</param>
        /// <param name="referer"></param>
        /// <returns></returns>
        public static string GetPageHTML(string url, Encoding encoding, out string responseUrl, string referer = "")
        {
            Stream stream = null;
            StreamReader sr = null;
            responseUrl = url;
            try
            {
                var req = (HttpWebRequest)WebRequest.Create(url);
                req.Method = "GET";
                req.Accept = "text/html,application/xhtml+xml,application/xml;";
                req.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36";
                if (!string.IsNullOrEmpty(referer))
                {
                    req.Referer = referer;
                }
                var response = (HttpWebResponse)req.GetResponse();
                responseUrl = response.ResponseUri == null ? url : response.ResponseUri.AbsoluteUri;
                stream = response.GetResponseStream();
                sr = new StreamReader(stream, encoding);
                return sr.ReadToEnd();
            }
            catch
            {
                return string.Empty;
            }
            finally
            {
                if (sr != null)
                {
                    sr.Close();
                    sr.Dispose();
                }

                if (stream != null)
                {
                    stream.Close();
                    stream.Dispose();
                }
            }
        }

    }
}
